package meijuli.com.join51.business.fragment;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.Map;
import meijuli.com.join51.business.BuildConfig;
import com.jhx.common.utils.Constants;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.activity.IpActivity;
import meijuli.com.join51.business.activity.MainActivity;

import com.jhx.common.cache.SimpleCache;
import com.jhx.common.model.DeviceInfo;
import com.jhx.common.http.IPServFactory;
import com.jhx.common.utils.SystemUtil;
import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import meijuli.com.join51.business.model.EventBean;
import com.jhx.common.model.User;
import meijuli.com.join51.business.model.UserData;
import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.ui.widget.ClearEditText;
import meijuli.com.join51.business.utils.SoftInputUtil;
import meijuli.com.join51.business.utils.StringUtil;
import com.jhx.common.utils.ToastUtil;
import com.jhx.common.utils.UserManager;
import retrofit2.Call;

/**
 * 登录页面
 *
 * @author jack
 */
public class LoginFragment extends BaseFragment implements View.OnClickListener {
    private Call<HttpResponse<UserData>> mCall;
    ClearEditText mobileInputView;
    ClearEditText passwordInputView;
    Button btnLogin;
    TextView registerView;
    TextView findPwdView;
    TextView mTextShowIp;
    /**
     * 密码规则，必须是数字和字母组合，并且在6-16位之间
     */
    private String regex = "^[0-9A-Za-z]{6,16}$";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SimpleCache.Companion.delete(Constants.TOKEN_ID);
        SimpleCache.Companion.delete(Constants.IS_LOGIN);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_login, container, false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mobileInputView = view.findViewById(R.id.mobile_input_view);
        passwordInputView = view.findViewById(R.id.password_input_view);
        btnLogin = view.findViewById(R.id.btn_confirm);
        registerView = view.findViewById(R.id.registerView);
        findPwdView = view.findViewById(R.id.findPwdView);
        mTextShowIp = view.findViewById(R.id.text_show_ip);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        registerView.setOnClickListener(this);
        findPwdView.setOnClickListener(this);
        btnLogin.setOnClickListener(this);
        registerView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG|Paint.ANTI_ALIAS_FLAG);
        findPwdView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG|Paint.ANTI_ALIAS_FLAG);

        mobileInputView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String currentContent = s.toString();
                if (!TextUtils.isEmpty(currentContent)) {
                    if (null != passwordInputView) {
                        String mobileContent = passwordInputView.getText().toString();
                        if (!TextUtils.isEmpty(mobileContent) && mobileContent.length() > 5) {
                            btnLogin.setEnabled(true);
                            return;
                        }
                    }
                }
                btnLogin.setEnabled(false);
            }
        });

        passwordInputView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String currentContent = s.toString();
                if (!TextUtils.isEmpty(currentContent) && currentContent.length() > 5) {
                    if (null != mobileInputView) {
                        String mobileContent = mobileInputView.getText().toString();
                        if (!TextUtils.isEmpty(mobileContent)) {
                            btnLogin.setEnabled(true);
                            return;
                        }
                    }
                }
                btnLogin.setEnabled(false);
            }
        });

        SoftInputUtil.get().hideSoftKeyboard(getActivity());

        User user = UserManager.get().getUser();
        if (user != null) {
            mobileInputView.clearFocus();
            passwordInputView.requestFocus();
            mobileInputView.setText(user.getPhone());
        }

        if (BuildConfig.DEBUG) {
            mTextShowIp.setVisibility(View.VISIBLE);
            mTextShowIp.setText(IPServFactory.sharedInstance().getNewServerName());
            mTextShowIp.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), IpActivity.class);
                    startActivity(intent);
                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_confirm:
                String mobileNumber = mobileInputView.getText().toString();
                String password = passwordInputView.getText().toString();
                if (TextUtils.isEmpty(mobileNumber) || mobileNumber.length() != 11) {
                    ToastUtil.getInstance().showToast("请输入正确的手机号码");
                    return;
                } else if (password.length() < 6 || password.length() > 16) {
                    ToastUtil.getInstance().showToast("密码为6-16之间，请重新输入");
                    return;
                }
                SoftInputUtil.get().hideSoftKeyboard(getActivity());
                login(mobileNumber, password);
                break;
            case R.id.findPwdView:
                switchFragment(this, new FindPwdFragment());
                break;
            case R.id.registerView:
                switchFragment(this, new RegisterFragment());
                break;
            default:

                break;
        }
    }

    private void login(final String mobileNumber, String password) {
        showLoadingDialog();
        mCall = ApiManager.get().getApiService(ApiService.class)
                .login(mobileNumber, StringUtil.encodeToSHA256(password), 2, getLoginParams());
        HttpRequest.getRequest().autoRecycle(this).start(mCall, new ResponseCallback<UserData>() {

            @Override
            public void onSuccess(String url, UserData data) {
                dismissDialog();
                if (data == null || data.getUser() == null) {
                    ToastUtil.getInstance().showToast(getActivity(), "登录失败");
                    return;
                }
                UserManager.get().setUser(data.getUser());
                SimpleCache.Companion.put(Constants.TOKEN_ID, data.getTokenID());
                SimpleCache.Companion.put(Constants.IS_LOGIN, true);
                SimpleCache.Companion.put(Constants.RECOMMEND_PHONE, "" + data.getRecommendPhone());
                UserManager.get().setDiscount(data.getUser().getDiscountNum());
                SimpleCache.Companion.put(Constants.PAY_MONEY_URL, data.getPayMoneyUrl());
                Intent intent = new Intent(getActivity(), MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(intent);
                dismissDialog();
                getActivity().finish();
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
            }
        });
    }

    public Map<String, String> getLoginParams() {
        Map<String, String> req = new HashMap<>();
        DeviceInfo deviceInfo = SystemUtil.getDeviceInfo();
        if (!TextUtils.isEmpty(deviceInfo.getOSVersion())) {
            req.put("clientOS", deviceInfo.getOSVersion());
        }
        if (!TextUtils.isEmpty(deviceInfo.getNetworkType())) {
            req.put("clientNet", deviceInfo.getNetworkType());
        }
        if (!TextUtils.isEmpty(deviceInfo.getMAC())) {
            req.put("macAddress", deviceInfo.getMAC());
        }
        // 表示Android平台
        req.put("clientType", "1");
        return req;
    }

    @Subscribe()
    public void onEvent(EventBean eventBean) {
        switch (eventBean.getStatus()) {
            case EventBean.STATUS_REGISTER:
                String phone = (String) eventBean.getEvent();
                if (phone == null) {
                    return;
                }
                mobileInputView.setText(phone);
                break;
            default:

                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

}
